#include "head.h"

void OPEN_ERR(int fd)
{
    if (fd == -1)
    {
        perror("Error");
    }
}

int main(int argc, char const *argv[])
{
    int fd = open(argv[1], O_RDWR, 0666);
    OPEN_ERR(fd);
    char buffer[1024];
    size_t bytes;
    int char_count = 0, word_count = 0, line_count = 0;
    int in_word = 0;
    while ((bytes = read(fd, buffer, sizeof(buffer))) > 0)
    {
        for (size_t i = 0; i < bytes; i++)
        {
            char c = buffer[i];
            char_count++;

            if (c == '\n')
            {
                line_count++;
            }

            if (c == ' ' || c == '\n' || c == '\t')
            {
                if (in_word)
                {
                    word_count++;
                    in_word = 0;
                }
            }
            else
            {
                in_word = 1;
            }
        }

        if (in_word)
        {
            word_count++;
            in_word = 0;
        }
    }
    printf("字符: %d\n", char_count);
    printf("单词: %d\n", word_count);
    printf("行数: %d\n", line_count);
}